package com.zrrd.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zrrd.reggie.bean.Category;
import com.zrrd.reggie.bean.Dish;
import com.zrrd.reggie.bean.Flavor;
import com.zrrd.reggie.bean.dto.DishDto;
import com.zrrd.reggie.common.R;
import com.zrrd.reggie.service.CategoryService;
import com.zrrd.reggie.service.DishService;
import com.zrrd.reggie.service.FlavorService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@RestController
@RequestMapping("/dish")
public class DishController {

    @Autowired
    private DishService dishService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private FlavorService flavorService;
    @Autowired
    private RedisTemplate redisTemplate;

    //分页查询菜品
    @GetMapping("/page")
    public R<Page> page(Integer page, Integer pageSize, String name) {
        //创建菜品分页对象
        Page<Dish> pageInfo = new Page<>(page, pageSize);
        //创建条件构造器
        QueryWrapper<Dish> wrapper = new QueryWrapper<>();
        //设置排序
        wrapper.orderByDesc("sort");
        //如果传过来的name不为空 作为模糊查询的条件
        if (name != null && !name.equals("")) {
            wrapper.like("name", name);
        }
        //执行分页处理
        dishService.page(pageInfo, wrapper);
        //创建菜品dto分页对象
        Page<DishDto> pagedto = new Page<>();
        //对象的属性复制（将菜品的分页对象中的菜品属性复制）
        BeanUtils.copyProperties(pageInfo, pagedto, "records");
        //获取菜品分页对象的菜品集合数据
        List<Dish> dishList = pageInfo.getRecords();
        //创建一个dto的菜品对象集合
        List<DishDto> dishDtoList = new ArrayList<>();
        //遍历菜品集合
        for (Dish dish : dishList) {
            //创建dto对象
            DishDto dto = new DishDto();
            //将当前dish对象的属性复制到dto中
            BeanUtils.copyProperties(dish, dto);
            //根据分类id查询的分类对象
            Category category = categoryService.getOne(new QueryWrapper<Category>().eq("id", dish.getCategoryId()));
            //如果当前分类不为空
            if (category != null) {
                //给设置的dto对象设置分类名称
                dto.setCategoryName(category.getName());
                //将dto对象添加进dto集合
                dishDtoList.add(dto);
            }
        }
        //给dto的分页对象 重新设置集合
        pagedto.setRecords(dishDtoList);
        //返回dto分页对象
        return R.success(pagedto);
    }

    //新增菜品
    @CacheEvict(value = "dishCache" ,allEntries = true)
    @PostMapping
    public R<String> save(@RequestBody DishDto dto) {
        dishService.saveDish(dto);
        return R.success("添加成功");
    }

    //根据id获取菜品信息
    @GetMapping("/{id}")
    public R<DishDto> getDishWithFlavor(@PathVariable("id") Long id) {
        DishDto dto = dishService.getDishWithFlavor(id);
        return R.success(dto);
    }

    //修改菜品
    @CacheEvict(value = "dishCache" ,allEntries = true)
    @PutMapping
    public R<String> update(@RequestBody DishDto dto) {
        dishService.updateDish(dto);
        return R.success("修改成功");
    }

    //批量停售起售
    @CacheEvict(value = "dishCache" ,allEntries = true)
    @PostMapping("/status/{status}")
    public R<String> updateStatus(@PathVariable("status") Integer status, Long[] ids) {

        boolean a = true;
        for (Long id : ids) {
            Dish dish = new Dish();
            dish.setId(id);
            dish.setStatus(status);
            boolean b = dishService.updateById(dish);
            a = a && b;
        }
        return a ? R.success("修改菜品状态成功") : R.error("修改菜品状态失败");
    }

    //批量删除
    @CacheEvict(value = "dishCache" ,allEntries = true)
    @DeleteMapping
    public R<String> delete(Long[] ids) {
        dishService.removeByIds(Arrays.asList(ids));
        //删除缓存中所有分类下的所有菜品
        return R.success("删除菜品成功");
    }

    //根据分类id查菜品
    @Cacheable(value = "dishCache" ,key = "#dish.categoryId+'_'+#dish.status")
    @GetMapping("/list")
    public R<List> list(Dish dish) {
        QueryWrapper<Dish> wrapper = new QueryWrapper<>();
        wrapper.eq("category_id", dish.getCategoryId());
        if(dish.getStatus() != null) {
            wrapper.eq("status", dish.getStatus());
        }
        wrapper.orderByDesc("sort");
        List<Dish> dishList = dishService.list(wrapper);
        List<DishDto> dtoList = new ArrayList<>();
        //遍历
        for (Dish d : dishList) {
            DishDto dto = new DishDto();
            BeanUtils.copyProperties(d, dto);
            QueryWrapper<Flavor> flavorQueryWrapper = new QueryWrapper<>();
            flavorQueryWrapper.eq("dish_id", d.getId());
            List<Flavor> flavorList = flavorService.list(flavorQueryWrapper);
            dto.setFlavors(flavorList);
            dtoList.add(dto);
        }
        return R.success(dtoList);
        
    }
}
